package com.zly.framework.rbac.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zly.framework.rbac.configuration.SysAuthConfiguration;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * MybatisPlus字段填充
 *
 * @author 钟刘扬
 * @createtime 2024/6/1
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private SysAuthConfiguration sysAuthConfiguration;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String ANONYMOUS_USER = "anonymousUser";


    private static final String CREATE_BY = "createBy";

    private static final String CREATE_TIME = "createTime";

    private static final String UPDATE_BY = "updateBy";

    private static final String UPDATE_TIME = "updateTime";

    private static final String DEFAULT_STR = "API接口";

    @Override
    @Schema(name = "新增填充")
    public void insertFill(MetaObject metaObject) {
        String REDIS_PRE = sysAuthConfiguration.getRedis().getCaptcha();
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (!Objects.equals(ANONYMOUS_USER, principal.toString())) {
                String str = stringRedisTemplate.opsForValue().get(REDIS_PRE + principal);
                this.setFieldValByName(CREATE_BY, Objects.requireNonNullElse(str, principal), metaObject);
            }
            this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
        } catch (NullPointerException e) {
            this.setFieldValByName(CREATE_BY, DEFAULT_STR, metaObject);
            this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
        }
    }

    @Override
    @Schema(name = "编辑填充")
    public void updateFill(MetaObject metaObject) {
        String REDIS_PRE = sysAuthConfiguration.getRedis().getCaptcha();
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (!Objects.equals(ANONYMOUS_USER, principal.toString())) {
                this.setFieldValByName(UPDATE_BY, principal, metaObject);
                String str = stringRedisTemplate.opsForValue().get(REDIS_PRE + principal);
                this.setFieldValByName(UPDATE_BY, Objects.requireNonNullElse(str, principal), metaObject);
            }
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        } catch (NullPointerException e) {
            this.setFieldValByName(UPDATE_BY, DEFAULT_STR, metaObject);
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
    }
}

